<template>
  <div class="notifications-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>通知中心</span>
          <div class="header-actions">
            <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="badge">
              <el-icon size="20"><Bell /></el-icon>
            </el-badge>
            <span class="unread-text" v-if="unreadCount > 0">未读: {{ unreadCount }}</span>
          </div>
        </div>
      </template>

      <div v-loading="loading" class="notifications-list">
        <div
          v-for="notification in notifications"
          :key="notification.id"
          class="notification-item"
          :class="{ 'unread': !notification.isRead }"
          @click="handleMarkAsRead(notification)"
        >
          <div class="notification-content">
            <div class="notification-header">
              <el-icon class="notification-icon" :class="{ 'unread-icon': !notification.isRead }">
                <BellFilled v-if="!notification.isRead" />
                <Bell v-else />
              </el-icon>
              <span class="notification-title">{{ notification.title }}</span>
              <el-tag v-if="!notification.isRead" type="warning" size="small">未读</el-tag>
            </div>
            <p class="notification-message">{{ notification.content }}</p>
            <span class="notification-time">{{ formatTime(notification.createdAt) }}</span>
          </div>
          <div class="notification-actions">
            <el-button
              v-if="!notification.isRead"
              type="primary"
              size="small"
              text
              @click.stop="handleMarkAsRead(notification)"
            >
              标记已读
            </el-button>
            <el-button
              type="danger"
              size="small"
              text
              @click.stop="handleDelete(notification)"
            >
              删除
            </el-button>
          </div>
        </div>

        <el-empty v-if="!loading && notifications.length === 0" description="暂无通知" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell, BellFilled } from '@element-plus/icons-vue'
import { notificationAPI } from '../services/api'

const notifications = ref([])
const unreadCount = ref(0)
const loading = ref(false)
let timer = null

const fetchNotifications = async () => {
  loading.value = true
  try {
    const [notificationsResponse, countResponse] = await Promise.all([
      notificationAPI.getNotifications(),
      notificationAPI.getUnreadCount()
    ])
    notifications.value = notificationsResponse.notifications || []
    unreadCount.value = countResponse.count || 0
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取通知列表失败')
  } finally {
    loading.value = false
  }
}

const handleMarkAsRead = async (notification) => {
  if (notification.isRead) return
  
  try {
    await notificationAPI.markAsRead(notification.id)
    notification.isRead = true
    unreadCount.value = Math.max(0, unreadCount.value - 1)
    ElMessage.success('已标记为已读')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '标记失败')
  }
}

const handleDelete = async (notification) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await notificationAPI.deleteNotification(notification.id)
    const index = notifications.value.findIndex(n => n.id === notification.id)
    if (index > -1) {
      if (!notification.isRead) {
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
      notifications.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

// 定期刷新未读数量
const startPolling = () => {
  timer = setInterval(async () => {
    try {
      const response = await notificationAPI.getUnreadCount()
      unreadCount.value = response.count || 0
    } catch (error) {
      // 静默失败
    }
  }, 30000) // 每30秒刷新一次
}

onMounted(() => {
  fetchNotifications()
  startPolling()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.notifications-container {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.badge {
  cursor: pointer;
}

.unread-text {
  font-size: 14px;
  color: #f56c6c;
  font-weight: 500;
}

.notifications-list {
  min-height: 400px;
}

.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s ease;
}

.notification-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transform: translateX(4px);
}

.notification-item.unread {
  border-left-color: #409eff;
  background: #f0f9ff;
}

.notification-content {
  flex: 1;
}

.notification-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.notification-icon {
  font-size: 18px;
  color: #909399;
}

.notification-icon.unread-icon {
  color: #409eff;
}

.notification-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.notification-message {
  font-size: 14px;
  color: #606266;
  margin: 8px 0;
  line-height: 1.6;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-actions {
  display: flex;
  gap: 8px;
  margin-left: 16px;
}
</style>

